package com.zt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.annotation.AdminLog;
import com.zt.common.Result;
import com.zt.entity.Admin;
import com.zt.service.AdminService;
import com.zt.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    @AdminLog(module = "系统管理", operation = "登录", description = "管理员登录系统", includeResult = false, type = AdminLog.OperationType.CREATE)
    public Result<LoginVO> login(@RequestBody Admin admin) {
        return Result.success(adminService.login(admin.getUsername(), admin.getPassword()));
    }

    @GetMapping("/info")
    public Result<Admin> getCurrentAdmin() {
        return Result.success(adminService.getCurrentAdmin());
    }

    @PostMapping
    @AdminLog(module = "管理员管理", operation = "新增", description = "新增管理员", type = AdminLog.OperationType.CREATE)
    public Result<Boolean> add(@RequestBody Admin admin) {
        return Result.success(adminService.save(admin));
    }

    @PutMapping
    @AdminLog(module = "管理员管理", operation = "修改", description = "修改管理员信息", type = AdminLog.OperationType.UPDATE)
    public Result<Boolean> update(@RequestBody Admin admin) {
        return Result.success(adminService.updateById(admin));
    }

    @DeleteMapping("/{id}")
    @AdminLog(module = "管理员管理", operation = "删除", description = "删除管理员", type = AdminLog.OperationType.DELETE)
    public Result<Boolean> delete(@PathVariable Long id) {
        return Result.success(adminService.removeById(id));
    }

    @GetMapping("/{id}")
    public Result<Admin> getById(@PathVariable Long id) {
        return Result.success(adminService.getById(id));
    }

    @GetMapping("/page")
    public Result<Page<Admin>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {
        Page<Admin> page = new Page<>(current, size);
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name)) {
            wrapper.like(Admin::getName, name);
        }
        return Result.success(adminService.page(page, wrapper));
    }

    @PostMapping("/logout")
    public Result<Void> logout() {
        adminService.logout();
        return Result.success();
    }

    @PostMapping("/updatePassword")
    public Result<Boolean> updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {
        return Result.success(adminService.updatePassword(oldPassword, newPassword));
    }
} 
